import {
  Breadcrumb,
  Button,
  Card,
  Form,
  Input,
  message,
  Modal,
  Radio,
  Upload,
} from 'antd';
import Channle from 'components/Cannle';
import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import styles from './index.module.scss';
import { getToken } from 'utils/storage';
import { baseURL } from 'utils/request';
import { UploadOutlined } from '@ant-design/icons';
import { getArticleListAPI, loadArticleById, publishArticleLsit, uploadArticleLsitId } from 'api/article';
import { useRef } from 'react/cjs/react.development';
export default function ArticlePublish(prop) {
  const handleFinish = async (values) => {
    if (showFileList.length !== type) {
      return message.warning('图片数量不正确')
  }

    console.log(9, values);
    let formDate = {
      ...values,
    };
    console.log(18, fileList);
    formDate.cover = {
      type: values.type,
      images:
      //   articleId ?
      showFileList.map((item) => item.response? item.response.data.url:  item.url)
      // :  showFileList.map((item) => item.response.data.url),
    };
    delete formDate.type;
    console.log(24, formDate);

    if (articleId) {
      await uploadArticleLsitId(articleId,formDate, draftRef.current);
      message.success('编辑成功');
    } else {
       await publishArticleLsit(formDate, draftRef.current);
    message.success('发布成功');
    }

    prop.history.push('/list');



  };
  const [fileList, setFileList] = useState([]);
  const [imgSrc, setImgSrc] = useState('');
  const [type, setType] = useState(1);
  const draftRef = useRef(false)
  const fromRef = useRef({})
  const props = {
    accept: '.png,.jpg,.jpeg',
    name: 'image',
    action: `${baseURL}/v1_0/upload`,
    headers: {
      authorization: `Bearer${getToken()}`,
    },
    onChange(info) {
      setFileList(info.fileList);
      // if (info.file.status !== 'uploading') {
      //     console.log(15, info.file, info.lileList);
      // }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 上传成功`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
      }
    },
    onPreview(file) {
      console.log(26, file);
      setImgSrc(file.thumbUrl || file.url);
    },
    beforeUpload(file) {
      const imgs = ['image/jpg', 'image/jpeg', 'image/png'];

      if (!imgs.includes(file.type)) {
        message.warning('不允许的文件类型');
        return Upload.LIST_IGNORE;
      }
    },
  };

  const onValuesChange = (changedValues, allValues) => {
    // console.log(56, allValues);
    if (changedValues.type !== undefined) {
      setType(changedValues.type);
    }
  };

  const showFileList = fileList.filter((item, index) => {
    if (type === 0) return false;
    if (type === 1) return index === 0;
    return true;
  });

  const articleId = prop.match.params.id;

  const loadArticleById = async (id) => {
    const res = await getArticleListAPI(id)
    console.log(101, res);
    fromRef.current.setFieldsValue({ ...res.data, type: res.data.cover.type })
    setType(res.data.cover.type)
    setFileList(res.data.cover.images.map(item => ({url:item})))
  }

  useEffect(() => {
    if (articleId) {
      loadArticleById(articleId)
  }

  }, [])

  return (
    <div style={{ padding: 24 ,height:'clac (100vh - 64px',overflow:'auto'}} className={styles.root}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>{`${articleId?'编辑':'发布'}`}文章</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          labelCol={{ span: 2 }}
          wrapperCol={{ span: 22 }}
          autoComplete="off"
          size="large"
          onFinish={handleFinish}
          initialValues={{
            channel_id: 0,
            content: '',
            type: 1,
          }}
          onValuesChange={onValuesChange}
          ref={fromRef}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[
              {
                required: true,
                message: '请输入标题',
              },
            ]}
          >
            <Input placeholder="请输入标题" />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[
              {
                required: true,
                message: '请选择频道',
              },
            ]}
          >
            <Channle></Channle>
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[
              {
                required: true,
                message: '请输入内容',
                validator(_, value) {
                  //  console.log(60, value);
                  if (value === '<p><br></p>' || !value) {
                    return Promise.reject(new Error('内容不能为空'));
                  }
                  return Promise.resolve();
                },
              },
            ]}
          >
            <ReactQuill
              theme="snow"
              placeholder="请输入文章内容..."
            ></ReactQuill>
          </Form.Item>

          <Form.Item label="封面" name="type">
            <Radio.Group>
              <Radio value={1}>单图</Radio>
              <Radio value={3}>三图</Radio>
              <Radio value={0}>无图</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item name="test">
            <Upload {...props} listType="picture-card" fileList={showFileList}>
              {/* 4.判断fileList的数量， 是否显示按钮 */}
              {fileList.length < type && <UploadOutlined />}
            </Upload>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" style={{ marginLeft: 80 }}>
            {`${articleId?'编辑':'发布'}`}文章
            </Button>
            <Button htmlType="submit"   style={{ marginLeft: 20 }} onClick={()=> draftRef.current = true}>
              存草稿
            </Button>
          </Form.Item>
        </Form>
      </Card>

      <Modal
        title="Basic Modal"
        visible={!!imgSrc}
        footer={null}
        onCancel={() => setImgSrc('')}
      >
        <img src={imgSrc} alt="" width={490} style={{ objectFit: 'cover' }} />
      </Modal>
    </div>
  );
}
